<template>
	<div class="search">
		<!-- 搜索栏 -->
		<form action="/">
			<van-search v-model="searchText" placeholder="请输入搜索关键词" show-action @search="onSearch(searchText)" @cancel="$router.back()"
			 @focus="isResultShow = false" />
		</form>
		<!-- 搜索栏 -->
		<!-- 搜索结果 -->
		<search-results v-if="isResultShow" :search-text="searchText"/>
		<!-- 搜索结果 -->
		
		<!-- 联想建议 -->
		<search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch"/>
		<!-- 联想建议 -->
		
		<!-- 历史记录 -->
		<search-history v-else :search-histories="searchHistories" @search="onSearch" @update-histories= "searchHistories = $event"/>
		<!-- 历史记录 -->
		
		
		
	</div>
</template>

<script>
	import SearchSuggestion from './components/search-suggestion.vue'
	import SearchHistory from './components/search-history.vue'
	import SearchResults from './components/search-results.vue'
	import { setItem,getItem } from '../../utils/storage.js'
	import { getSearchHistories } from '../../utils/search.js'
	import { mapState } from 'vuex'
	
	export default {
		name: 'Search',
		data() {
			return {
				searchText:'',
				isResultShow: false,
				searchHistories: [],
				
			}
		},
		components: {
			SearchSuggestion,
			SearchHistory,
			SearchResults
		},
		methods:{
			onSearch(searchText) {
				this.searchText = searchText
				
				const index = this.searchHistories.indexOf(searchText)
				if(index !== -1) {
					//把重复的历史记录删除
					this.searchHistories.splice(index,1)
				}
				//把最新的历史记录放到顶部
				this.searchHistories.unshift(searchText)
				
				setItem('search-histories',this.searchHistories)
				
			  this.isResultShow = true
			},
			async loadSearchHistories() {
				let searchHistories = getItem('search-histories') || []
				if(this.user) {
					const { data } = await getSearchHistories ()
					searchHistories = [...new Set([...searchHistories,...data.data.keywords])]
				}
				
				this.searchHistories = searchHistories
				
			}
			
		},
	 created() {
			this.loadSearchHistories()
		},
		computed: {
			...mapState['user']
		},
		watch:{
			searchHistories() {
				setItem('search-histories',this.searchHistories)
			}
		}
	}
</script>

<style>
</style>
